package top.zerozoo.learn.grade.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter("*.do")
public class LoginFilter implements Filter {
    private List<String> pathWhiteList = new ArrayList<>();

    @Override
    public void init(FilterConfig config) throws ServletException {
        pathWhiteList.add("/login.do");
        pathWhiteList.add("/queryScore.do");
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String path = httpRequest.getServletPath();
        if (pathWhiteList.contains(path) || httpRequest.getSession().getAttribute("adminInfo") != null) {
            chain.doFilter(request, response);
            return;
        }
        httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.do");
    }
}
